package com.louis.ylog;

import ch.qos.logback.classic.LoggerContext;
import com.louis.ylog.appender.CATAppender;
import com.louis.ylog.appender.ELKAppender;
import com.louis.ylog.feign.CatFeignConfiguration;
import com.louis.ylog.starter.CATConfig;
import com.louis.ylog.starter.ELKConfig;
import com.louis.ylog.starter.YLogProperties;
import com.louis.ylog.util.AopImporter;
import com.louis.ylog.util.FakeBean;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.*;

@Slf4j
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties({YLogProperties.class, CATConfig.class, ELKConfig.class})
@Import({FakeBean.class, AopImporter.class, CatFeignConfiguration.class})
@ConditionalOnProperty(value = "ylog.enable-y-log", havingValue = "true")
public class YLogAutoConfiguration implements InitializingBean{

    @Autowired
    private YLogProperties logProperties;

    @Override
    public void afterPropertiesSet(){
        if(logProperties==null||!logProperties.isEnableYLog()){
            log.info("未启用YLog日志收集");
            return;
        }

        boolean isCatEnable=(logProperties.getCat()!=null&&logProperties.getCat().isEnableCat());
        boolean isELKEnalbe=(logProperties.getElk()!=null&&logProperties.getElk().isEnableElk());

        if(!isCatEnable &&!isELKEnalbe){
            log.info("YLog日志收集中的ELK, CAT模块都未启用");
            return;
        }

        try {
            //设置ELK中的环境和应用
            TraceContext.setAppName(logProperties.getAppName());
            TraceContext.setEnv(logProperties.getEnv());

            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

            if(isELKEnalbe){
                ELKAppender appender=new ELKAppender(logProperties);
                appender.setName("ELKAppender-LogStash");
                appender.start();
                //添加appender
                appender.setContext(loggerContext);
                loggerContext.getLogger("ROOT").addAppender(appender);
            }

            if(isCatEnable){
                CATAppender catAppender=new CATAppender(logProperties);
                catAppender.setName("CATAppender-CAT");
                catAppender.start();
                catAppender.setContext(loggerContext);
                loggerContext.getLogger("ROOT").addAppender(catAppender);
            }

            TraceContext.setCatEnable(isCatEnable);
            TraceContext.setElkEnable(isELKEnalbe);

        }catch (Exception e){
            log.error("YLog启动异常",e);
        }
    }

}
